#include "wav_to_bin.h"

int	size_head(char *file)
{
  FILE *ffile = NULL;
  unsigned int file_size = 0, data_size = 0, res = 0;

  ffile = fopen(file, "r");
  fseek(ffile, 4, SEEK_CUR);

  fread(&file_size, sizeof (int), 1, ffile);
  file_size += 8;

  fseek(ffile, 32, SEEK_CUR);
  fread(&data_size, sizeof (int), 1, ffile);

  fclose(ffile);

  res = file_size - data_size;

  if ((res != 44) & (res != 52) & (res != 56))
    return (-1);
  else
    return (res);

}

int	header(char *head)
{
  FILE *fhead = NULL;
  unsigned int riff;
  unsigned int wave;
  unsigned short int echant;
  unsigned int hexa_riff = 1179011410, hexa_wave = 1163280727;

  fhead = fopen(head, "r");
  fread(&riff, sizeof (int), 1, fhead);
  fseek(fhead, 4, SEEK_CUR);
  fread(&wave, sizeof (int), 1, fhead);
  fseek(fhead, 22, SEEK_CUR);
  fread(&echant, sizeof (short int), 1, fhead);

  if (riff != hexa_riff)
    return (-2);
  if (wave != hexa_wave)
    return (-2);

  fclose(fhead);

  if ((echant == 8) || (echant == 16) || (echant == 24))
    return (echant);
  else
    return (-2);
}

/* function use to extract .wav data, like size, echant kind... */
/* result header.txt and binary.txt */

int	text(char *file)
{
  FILE *fd, *fout, *fheader;
  int i = 1, res = 1;
  unsigned char *wav = NULL;
  unsigned char *audio_data = NULL;
  unsigned int head_size = 0;

  head_size = size_head(file);
  res = head_size;
  if (res != -1)
  {
    wav = malloc(head_size * sizeof (char));
    fd = fopen(file, "r");
    fheader = fopen("header.txt", "w");
    fout = fopen("binary.txt", "w");
    fread(wav, sizeof (char), head_size, fd);
    fwrite(wav, sizeof (char), head_size, fheader);
    fclose(fheader);
    res = header("header.txt");
    if (res != -2)
    {
      while (!feof(fd))
      {
	audio_data = realloc(audio_data, NB_BYTE * i);
	fread(audio_data + (NB_BYTE * (i - 1)), sizeof (char), NB_BYTE, fd);
	fwrite(audio_data + (NB_BYTE * (i - 1)), sizeof (char), NB_BYTE, fout);
	i++;
      }
    }
    fclose(fd);
    fclose(fout);
    free(wav);
    free(audio_data);
  }
  return (res);
}
